package com.yhy.form.service;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.yhy.common.utils.YhyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yhy.form.dao.FormApplyFieldValueDao;
import com.yhy.form.vo.FormApplyFieldValueVO;
import com.yhy.common.service.BaseService;

import java.math.BigDecimal;
import java.util.*;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 20-3-17 下午3:36 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2020<br>
 *  *
 *
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class FormApplyFieldValueService extends BaseService<FormApplyFieldValueVO> {

	@Autowired
	private  FormApplyFieldValueDao formApplyFieldValueDao;

	@Override
	protected FormApplyFieldValueDao getDao() {
		return formApplyFieldValueDao;
	}

	public List<FormApplyFieldValueVO> findByMainId(String mainId) {
		return 	getDao().findByMainId(mainId);
	}

	public Map<String,Object> convert2FormDataMap(List<FormApplyFieldValueVO> fieldValueVOList) {
		Map<String,Object> rtnMap = Maps.newHashMap();
		fieldValueVOList.stream().forEach(vo -> {
			rtnMap.put(vo.getFieldControlId(), str2Object(vo.getFieldValue()));
		});
		return rtnMap;
	}

	public String arrStr2Str(String fieldValue) {
		if(fieldValue.startsWith("[") && fieldValue.endsWith("]")) {
			String valueStr = fieldValue.replaceFirst("\\[", "").replaceFirst("]","").replaceAll("\"","");
			return valueStr;
		}
		return null;
	}

	private Object str2Object(String fieldValue) {
		if(StringUtils.isBlank(fieldValue)) {
			return "";
		}
		if("true".equalsIgnoreCase(fieldValue) || "false".equalsIgnoreCase(fieldValue)) {
			return new Boolean(fieldValue);
		}
		if(fieldValue.startsWith("[") && fieldValue.endsWith("]")) {
			String valueStr = arrStr2Str(fieldValue);
			Set<Object> valSet = Sets.newHashSet();
			for (String val : valueStr.split(",")) {
				valSet.add(YhyUtils.isNumeric(val) ? new Float(val) : val);
			}
			return valSet;
		}
		if(YhyUtils.isNumeric(fieldValue)) {
			return new BigDecimal(fieldValue);
		}
		return fieldValue;
	}

}
